part of 'page.dart';

class _GoogleAppleStorePurchasePageView extends StatelessWidget with ScreenUtilMixin {
  const _GoogleAppleStorePurchasePageView({
    required _GoogleAppleStorePurchasePageWloc wloc,
  }) : _wloc = wloc;

  final _GoogleAppleStorePurchasePageWloc _wloc;

  Widget _buildContent({
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    return Scrollbar(
      child: SingleChildScrollView(
        physics: const BouncingScrollPhysics(),
        child: Container(
          width: double.infinity,
          color: GoogleAppleStorePurchasePageTheme.of(context).backgroundColor,
          child: Column(
            children: [
              Transform.translate(
                offset: const Offset(0.0, -1.0),
                child: _buildGoogleAppleStorePurchaseBlock(
                  state: state,
                  context: context,
                ),
              ),
              SizedBox(
                height: 32 * logWidthScaleFactor,
              ),
              _buildPremiumFeatures(
                context: context,
              ),
              SizedBox(
                height: 64 * logWidthScaleFactor,
              ),
              _buildDisclaimer(
                context: context,
              ),
              SafeArea(
                left: false,
                top: false,
                right: false,
                bottom: true,
                child: SizedBox(
                  height: 95 * logWidthScaleFactor,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGoogleAppleStorePurchaseBlock({
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    const kPurchaseItemTileHeight = 130.0;
    const kPurchaseItemTileFooterHeight = 18.0;

    final effectiveImageHeight = 200 * logWidthScaleFactor;
    final effectiveImageFloorHeight = 75 * logWidthScaleFactor;
    final effectivePurchaseItemTileHeight = kPurchaseItemTileHeight * logWidthScaleFactor;
    final effectivePurchaseItemTileFooterHeight =
        kPurchaseItemTileFooterHeight * logWidthScaleFactor;
    final imageFloorOverlappingHeight = effectiveImageFloorHeight * 0.45;
    final purchaseItemTileFloorOverlappingHeight = effectiveImageFloorHeight * 0.4;

    return Stack(
      children: [
        Column(
          children: [
            Container(
              width: double.infinity,
              color: GoogleAppleStorePurchasePageTheme.of(context).imageBackgroundColor,
              child: Column(
                children: [
                  SizedBox(
                    height: 32 * logWidthScaleFactor,
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 40 * logWidthScaleFactor,
                    ),
                    child: ConstrainedBox(
                      constraints: const BoxConstraints(
                        maxWidth: 600,
                      ),
                      child: Column(
                        children: [
                          Text(
                            GoogleAppleStorePurchasePageTranslation.of(context).title,
                            style: GoogleAppleStorePurchasePageTheme.of(context).textTheme.title,
                            textAlign: TextAlign.center,
                            textScaleFactor: logWidthScaleFactor,
                          ),
                          SizedBox(
                            height: 16 * logWidthScaleFactor,
                          ),
                          Text(
                            GoogleAppleStorePurchasePageTranslation.of(context).subtitle,
                            style: GoogleAppleStorePurchasePageTheme.of(context).textTheme.subtitle,
                            textAlign: TextAlign.center,
                            textScaleFactor: logWidthScaleFactor,
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 16 * logWidthScaleFactor,
                  ),
                  SizedBox(
                    height: effectiveImageHeight +
                        effectiveImageFloorHeight / 2 -
                        imageFloorOverlappingHeight,
                  ),
                ],
              ),
            ),
            SizedBox(
              height: effectiveImageFloorHeight / 2 +
                  effectivePurchaseItemTileHeight -
                  purchaseItemTileFloorOverlappingHeight +
                  effectivePurchaseItemTileFooterHeight,
            ),
          ],
        ),
        Positioned.fill(
          bottom: effectivePurchaseItemTileFooterHeight +
              effectivePurchaseItemTileHeight -
              purchaseItemTileFloorOverlappingHeight,
          child: Align(
            alignment: Alignment.bottomCenter,
            child: _PurchaseImageFloor(
              color: GoogleAppleStorePurchasePageTheme.of(context).imageFloorColor,
              height: effectiveImageFloorHeight,
            ),
          ),
        ),
        Positioned.fill(
          bottom: effectivePurchaseItemTileFooterHeight +
              effectivePurchaseItemTileHeight -
              purchaseItemTileFloorOverlappingHeight +
              effectiveImageFloorHeight -
              imageFloorOverlappingHeight,
          child: Align(
            alignment: Alignment.bottomCenter,
            child: SizedBox(
              height: effectiveImageHeight,
              child: Image.asset(
                'assets/images/purchase_image.webp',
                height: effectiveImageHeight,
                fit: BoxFit.cover,
                filterQuality: FilterQuality.medium,
              ),
            ),
          ),
        ),
        Positioned.fill(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: _buildPurchaseItemTiles(
              tileHeight: effectivePurchaseItemTileHeight,
              tileFooterHeight: effectivePurchaseItemTileFooterHeight,
              state: state,
              context: context,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPurchaseItemTiles({
    required double tileHeight,
    required double tileFooterHeight,
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 16 * logWidthScaleFactor,
      ),
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          maxWidth: 400,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(
              child: _buildMonthSubscriptionTile(
                tileHeight: tileHeight,
                tileFooterHeight: tileFooterHeight,
                state: state,
                context: context,
              ),
            ),
            SizedBox(
              width: 8 * logWidthScaleFactor,
            ),
            Expanded(
              child: _buildYearSubscriptionTile(
                tileHeight: tileHeight,
                tileFooterHeight: tileFooterHeight,
                state: state,
                context: context,
              ),
            ),
            SizedBox(
              width: 8 * logWidthScaleFactor,
            ),
            Expanded(
              child: _buildLifetimePurchaseTile(
                tileHeight: tileHeight,
                tileFooterHeight: tileFooterHeight,
                state: state,
                context: context,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMonthSubscriptionTile({
    required double tileHeight,
    required double tileFooterHeight,
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    final monthSubscriptionModel = state.monthSubscriptionModel;
    const months = 1;
    final durationLabel = GoogleAppleStorePurchasePageTranslation.of(context)
        .getPurchaseItemTileSubscriptionDurationLabel(
      months: months,
    );

    final String priceWithCurrency;

    if (monthSubscriptionModel.prettifiedPrice == null) {
      priceWithCurrency = monthSubscriptionModel.localizedStorePriceWithCurrency;
    } else {
      priceWithCurrency = HomeCoreTranslation.of(context).buildPurchaseItemPriceWithCurrency(
        price: monthSubscriptionModel.prettifiedPrice!,
        currency: monthSubscriptionModel.currency,
      )!;
    }

    final priceLabel =
        GoogleAppleStorePurchasePageTranslation.of(context).subscriptionTilePriceLabel;

    final selected = state.selectedPurchaseItemSku == monthSubscriptionModel.sku;

    return _PurchaseItemTile(
      effectiveHeight: tileHeight,
      effectiveFooterHeight: tileFooterHeight,
      duration: '$months',
      durationLabel: durationLabel,
      priceWithCurrency: priceWithCurrency,
      priceLabel: priceLabel,
      monthlyPriceLabel: null,
      selected: selected,
      showPopularityBadge: false,
      onTap: () {
        _wloc.onPurchaseItemTileTap(
          purchaseItemSku: monthSubscriptionModel.sku,
        );
      },
    );
  }

  Widget _buildYearSubscriptionTile({
    required double tileHeight,
    required double tileFooterHeight,
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    final yearSubscriptionModel = state.yearSubscriptionModel;

    const months = 12;
    final durationLabel = GoogleAppleStorePurchasePageTranslation.of(context)
        .getPurchaseItemTileSubscriptionDurationLabel(
      months: months,
    );

    final String priceWithCurrency;

    if (yearSubscriptionModel.prettifiedPrice == null) {
      priceWithCurrency = yearSubscriptionModel.localizedStorePriceWithCurrency;
    } else {
      priceWithCurrency = HomeCoreTranslation.of(context).buildPurchaseItemPriceWithCurrency(
        price: yearSubscriptionModel.prettifiedPrice!,
        currency: yearSubscriptionModel.currency,
      )!;
    }

    final priceLabel =
        GoogleAppleStorePurchasePageTranslation.of(context).subscriptionTilePriceLabel;

    final selected = state.selectedPurchaseItemSku == yearSubscriptionModel.sku;

    String? monthlyPriceLabel;
    if (yearSubscriptionModel.prettifiedMonthlyPrice != null) {
      final monthlyPriceWithCurrency =
          HomeCoreTranslation.of(context).buildPurchaseItemPriceWithCurrency(
        price: yearSubscriptionModel.prettifiedMonthlyPrice!,
        currency: yearSubscriptionModel.currency,
      )!;

      monthlyPriceLabel =
          GoogleAppleStorePurchasePageTranslation.of(context).buildMonthlyPriceLabel(
        monthlyPriceWithCurrency: monthlyPriceWithCurrency,
      );
    }

    return _PurchaseItemTile(
      effectiveHeight: tileHeight,
      effectiveFooterHeight: tileFooterHeight,
      duration: '$months',
      durationLabel: durationLabel,
      priceWithCurrency: priceWithCurrency,
      priceLabel: priceLabel,
      monthlyPriceLabel: monthlyPriceLabel,
      selected: selected,
      showPopularityBadge: true,
      onTap: () {
        _wloc.onPurchaseItemTileTap(
          purchaseItemSku: yearSubscriptionModel.sku,
        );
      },
    );
  }

  Widget _buildLifetimePurchaseTile({
    required double tileHeight,
    required double tileFooterHeight,
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    final lifetimePurchaseItemModel = state.lifetimePurchaseItemModel;

    const duration = '\u221e';
    final durationLabel = GoogleAppleStorePurchasePageTranslation.of(context)
        .purchaseItemTileLifetimePurchaseDurationLabel;

    final String priceWithCurrency;

    if (lifetimePurchaseItemModel.prettifiedPrice == null) {
      priceWithCurrency = lifetimePurchaseItemModel.localizedStorePriceWithCurrency;
    } else {
      priceWithCurrency = HomeCoreTranslation.of(context).buildPurchaseItemPriceWithCurrency(
        price: lifetimePurchaseItemModel.prettifiedPrice!,
        currency: lifetimePurchaseItemModel.currency,
      )!;
    }

    final selected = state.selectedPurchaseItemSku == lifetimePurchaseItemModel.sku;

    return _PurchaseItemTile(
      effectiveHeight: tileHeight,
      effectiveFooterHeight: tileFooterHeight,
      duration: duration,
      durationLabel: durationLabel,
      priceWithCurrency: priceWithCurrency,
      priceLabel: null,
      monthlyPriceLabel: null,
      selected: selected,
      showPopularityBadge: false,
      onTap: () {
        _wloc.onPurchaseItemTileTap(
          purchaseItemSku: lifetimePurchaseItemModel.sku,
        );
      },
    );
  }

  Widget _buildPremiumFeatures({
    required BuildContext context,
  }) {
    final iconSize = 30 * defaultScaleFactor;

    final premiumFeatureGap = SizedBox(
      height: 25 * logWidthScaleFactor,
    );

    return FractionallySizedBox(
      widthFactor: ScreenUtil().screenLayout.isPhoneLayout ? 1.0 : 0.75,
      child: Align(
        alignment: Alignment.centerLeft,
        child: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: 20 * logWidthScaleFactor,
          ),
          child: ConstrainedBox(
            constraints: const BoxConstraints(
              maxWidth: 600,
            ),
            child: Column(
              children: [
                _PremiumFeatureBlock(
                  title: GoogleAppleStorePurchasePageTranslation.of(context)
                      .dailyUnlimitPremiumFeatureTitle,
                  subtitle: GoogleAppleStorePurchasePageTranslation.of(context)
                      .dailyUnlimitPremiumFeatureSubtitle,
                  icon: Icon(
                    CupertinoIcons.infinite,
                    size: iconSize,
                    color: CoreTheme.of(context).primaryColor,
                  ),
                ),
                premiumFeatureGap,
                _PremiumFeatureBlock(
                  title: GoogleAppleStorePurchasePageTranslation.of(context)
                      .exerciseShufflingPremiumFeatureTitle,
                  subtitle: GoogleAppleStorePurchasePageTranslation.of(context)
                      .exerciseShufflingPremiumFeatureSubtitle,
                  icon: Icon(
                    CupertinoIcons.shuffle,
                    size: iconSize * 0.9,
                    color: CoreTheme.of(context).primaryColor,
                  ),
                ),
                premiumFeatureGap,
                _PremiumFeatureBlock(
                  title: GoogleAppleStorePurchasePageTranslation.of(context)
                      .allLearningContentPremiumFeatureTitle,
                  subtitle: GoogleAppleStorePurchasePageTranslation.of(context)
                      .allLearningContentPremiumFeatureSubtitle,
                  icon: Icon(
                    CupertinoIcons.plus_app,
                    size: iconSize,
                    color: CoreTheme.of(context).primaryColor,
                  ),
                ),
                premiumFeatureGap,
                _PremiumFeatureBlock(
                  title:
                      GoogleAppleStorePurchasePageTranslation.of(context).imagePremiumFeatureTitle,
                  subtitle: GoogleAppleStorePurchasePageTranslation.of(context)
                      .imagePremiumFeatureSubtitle,
                  icon: Icon(
                    CupertinoIcons.photo,
                    size: iconSize * 0.9,
                    color: CoreTheme.of(context).primaryColor,
                  ),
                ),
                premiumFeatureGap,
                _PremiumFeatureBlock(
                  title: GoogleAppleStorePurchasePageTranslation.of(context)
                      .themeCustomizationPremiumFeatureTitle,
                  subtitle: GoogleAppleStorePurchasePageTranslation.of(context)
                      .themeCustomizationPremiumFeatureSubtitle,
                  icon: Icon(
                    CupertinoIcons.paintbrush,
                    size: iconSize,
                    color: CoreTheme.of(context).primaryColor,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDisclaimer({
    required BuildContext context,
  }) {
    final disclaimer = switch (Config().platform) {
      Platform.ios => HomeCoreTranslation.of(context).appStorePurchaseDisclaimer,
      Platform.android => HomeCoreTranslation.of(context).googlePlayPurchaseDisclaimer,
    };

    final termsOfUseTapGestureRecognizer = TapGestureRecognizer();
    termsOfUseTapGestureRecognizer.onTap = _wloc.onTermsOfUseTap;

    final privacyPolicyTapGestureRecognizer = TapGestureRecognizer();
    privacyPolicyTapGestureRecognizer.onTap = _wloc.onPrivacyPolicyTap;

    final parts = disclaimer.split('#');
    final partTextSpans = <TextSpan>[];

    for (var i = 0; i < parts.length; i++) {
      if (i == 1) {
        final textSpan = TextSpan(
          text: parts[i],
          style: GoogleAppleStorePurchasePageTheme.of(context).textTheme.disclaimer.copyWith(
                color: CoreTheme.of(context).primaryColor,
              ),
          recognizer: termsOfUseTapGestureRecognizer,
        );

        partTextSpans.add(textSpan);
      } else if (i == 3) {
        partTextSpans.add(TextSpan(
          text: parts[i],
          style: GoogleAppleStorePurchasePageTheme.of(context).textTheme.disclaimer.copyWith(
                color: CoreTheme.of(context).primaryColor,
              ),
          recognizer: privacyPolicyTapGestureRecognizer,
        ));
      } else {
        partTextSpans.add(TextSpan(text: parts[i]));
      }
    }

    return Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 20 * logWidthScaleFactor,
      ),
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          maxWidth: 600,
        ),
        child: Text.rich(
          TextSpan(
            style: GoogleAppleStorePurchasePageTheme.of(context).textTheme.disclaimer,
            children: partTextSpans,
          ),
          textAlign: TextAlign.center,
          textScaleFactor: defaultScaleFactor,
        ),
      ),
    );
  }

  Widget _buildPageClosingButton({
    required BuildContext context,
  }) {
    return AppIconButton(
      icon: Icon(
        CustomBoldIcons.medium_xmark,
        size: 24 * defaultScaleFactor,
        color: GoogleAppleStorePurchasePageTheme.of(context).pageClosingIconColor,
      ),
      width: 40 * defaultScaleFactor,
      height: 40 * defaultScaleFactor,
      onPressed: Navigator.of(context).pop,
    );
  }

  Widget _buildPurchaseRequestButton({
    required _GoogleAppleStorePurchasePageWlocState state,
    required BuildContext context,
  }) {
    final Widget button;

    if (state.purchaseRequestInProgress) {
      button = OverlayButton(
        onPressed: null,
        child: CupertinoActivityIndicator(
          color: CoreTheme.of(context).primaryContrastingColor,
          radius: 10 * defaultScaleFactor,
        ),
      );
    } else {
      button = OverlayTextButton(
        title: GoogleAppleStorePurchasePageTranslation.of(context).purchaseRequestButtonTitle,
        onPressed: _wloc.onPurchaseRequestButtonPressed,
      );
    }

    return SafeArea(
      left: false,
      top: false,
      right: false,
      bottom: true,
      child: Padding(
        padding: EdgeInsets.all(20 * logWidthScaleFactor),
        child: button,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return PrimaryScrollController(
      controller: _wloc.scrollController,
      child: SizedBox.expand(
        child:
            WlocBuilder<_GoogleAppleStorePurchasePageWloc, _GoogleAppleStorePurchasePageWlocState>(
          wloc: _wloc,
          builder: (context, state) {
            return Stack(
              fit: StackFit.expand,
              children: [
                Container(
                  color: !_wloc.scrollController.hasClients || _wloc.scrollController.offset < 0
                      ? GoogleAppleStorePurchasePageTheme.of(context).imageBackgroundColor
                      : GoogleAppleStorePurchasePageTheme.of(context).backgroundColor,
                ),
                _buildContent(
                  state: state,
                  context: context,
                ),
                Positioned.fill(
                  top: 10 * defaultScaleFactor,
                  right: 10 * defaultScaleFactor,
                  child: Align(
                    alignment: Alignment.topRight,
                    child: _buildPageClosingButton(
                      context: context,
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: _buildPurchaseRequestButton(
                    state: state,
                    context: context,
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
